/**
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

package org.elephantt.webby;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Dispatches the request to request handlers and processes the responses.
 */
public class Dispatcher {
  private static final Log log = LogFactory.getLog(Dispatcher.class);

  private final RequestMapper requestMapper;
  private final RequestResponseFactory requestResponseFactory;
  private final Map<Class, Responder> responderMap = createClassResponderMap();
  private Responder defaultResponder = new RawResponder();

  /**
   * Override this to create a customer class-responder map.
   */
  public Map<Class, Responder> createClassResponderMap() {
    Map<Class, Responder> map = new HashMap<Class, Responder>();
    map.put(Redirect.class, new RedirectResponder());
    map.put(NotFound.class, new NotFoundResponder());
    map.put(HttpException.class, new HttpExceptionResponder());
    map.put(SimpleResponse.class, new SimpleResponder());
    return map;
  }

  public void setDefaultResponder(Responder defaultResponder) {
    this.defaultResponder = defaultResponder;
  }

  public Dispatcher(RequestMapper requestMapper, RequestResponseFactory requestResponseFactory) {
    this.requestMapper = requestMapper;
    this.requestResponseFactory = requestResponseFactory;
  }

  public Dispatcher(RequestMapper requestMapper) {
    this.requestMapper = requestMapper;
    requestResponseFactory = new SimpleRequestResponseFactory();
  }

  public void registerResponder(Class objectClass, Responder responder) {
    responderMap.put(objectClass, responder);
  }

  public void dispatch(HttpServletRequest request, HttpServletResponse response) throws IOException {
    RequestMapping requestMapping = requestMapper.map(request);
    Request appRequest = requestResponseFactory.createRequest(request, requestMapping != null ? requestMapping.getUrlParameterMap() : null);
    Response appResponse = requestResponseFactory.createResponse(response);

    if (requestMapping != null) {
      request.setAttribute(ServletRequestAttributes.REQUEST_MAPPING, requestMapping);

      try {
        Responder responder;

        Object controllerReturnValue;
        try {
          Method m = requestMapping.getRequestHandlerMethod();
          Class[] paramTypes = m.getParameterTypes();

          if (paramTypes.length == 2) {
            controllerReturnValue = requestMapping.getRequestHandlerMethod().invoke(requestMapping.getRequestHandler(), appRequest, appResponse);
          } else if (paramTypes.length == 1) {
            controllerReturnValue = requestMapping.getRequestHandlerMethod().invoke(requestMapping.getRequestHandler(), appRequest);
          } else if (paramTypes.length == 0) {
            controllerReturnValue = requestMapping.getRequestHandlerMethod().invoke(requestMapping.getRequestHandler());
          } else {
            throw new AssertionError("expected 0, 1, or 2 parameters");
          }
        } catch (IllegalAccessException e) {
          log.error("could not invoke controller", e);
          controllerReturnValue = new HttpException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (InvocationTargetException e) {
          log.error("could not invoke controller", e);
          controllerReturnValue = new HttpException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (HttpException e) {
          controllerReturnValue = e;
        }

        if (controllerReturnValue != null) {
          if (controllerReturnValue instanceof Responder) {
            responder = (Responder) controllerReturnValue;
          } else {
            responder = responderMap.get(controllerReturnValue.getClass());

            if (responder == null) {
              responder = defaultResponder;
            }
          }
        } else {
          // assume the controller handled the output
          responder = null;
        }

        if (responder != null) {
          responder.respond(request, response, controllerReturnValue);
        }
      } catch (Exception e) {
        log.error("Error serving request: " + appRequest.toString(), e);
        request.setAttribute("javax.servlet.error.exception", e);
        response.sendError(500);
      }
    } else {
      ErrorResponse.notFound.respond(request, response);
    }
  }
}